'use strict';

exports.main = async (event, context) => {
    const data = await uniCloud.request({
        url: "https://api.weixin.qq.com/sns/jscode2session",
        method: 'GET',
        data: {
            appid: 'wxf6ab670df0a89e37',
            secret: '51529562462349b6aebfc6c9c3950b31',
            js_code: event.code,
            grant_type: 'authorization_code'
        }
    })
	
	try{
		// 成功获取 wxOpenid，查询数据库判断一下是否已经注册
		const res = await uniCloud.database().collection("users").where({
		    wxOpenid: data.data.openid
		}).get()
		
		
		if (!res?.data?.length) {
		   return {
			 code: 0,
			 message: '该微信未绑定'
		   }
		}
		// if (user.data.length === 0) {
		// 	return {
		// 	  code: 400,
		// 	  message: '该微信未绑定'
		// 	}
		//   }
		
		
		//返回用户信息给前端
		// return res?.data?.[0]
		// return res.data[0]
		return {
			code: 200,
			message: '登录成功',
			data: res.data[0]
		}
	} catch(e) {
		return e
	}


};